package com.zenika.zentracker.hibernate.info;

import java.util.Collection;
import java.util.Iterator;

/**
 * Abstract class for all CollectionInformation.<br/>
 * 
 * Two things can happen in a collection:
 * <ul>
 * <li>Objects can be added</li>
 * <li>Objects can be removed</li>
 * </ul>
 * 
 * In Hibernate those modification can happen when a collection is recreated, removed or updated.<br/> For logging
 * purpose, the flush index before transaction completion is needed.<br/>
 * 
 * @author Zenika
 */
public abstract class AbstractCollectionInformation implements CollectionInformation {

    private final static String REMOVED = "REMOVED";
    private final static String ADDED = "ADDED";

    private int flushNumber;

    /**
     * Basic constructor needing the flush index before transaction completion.
     * 
     * @param flushIndex
     */
    protected AbstractCollectionInformation(int flushIndex) {
        this.flushNumber = flushIndex;
    }

    /**
     * Logging of all the elements added into a collection.
     * 
     * @param addedObjects the newly added objects
     * @return String to be added to the logs
     */
    protected String logAddingElementsInCollection(Collection addedObjects) {
        return logCollectionInformation(ADDED, addedObjects);
    }

    /**
     * Logging of all the elements removed from a collection.
     * 
     * @param removedObjects the objects removed from a collection
     * @return String to be added to the logs
     */
    protected String logRemovingElementsFromCollection(Collection removedObjects) {
        return logCollectionInformation(REMOVED, removedObjects);
    }

    /**
     * Logging message taking into account the flush index and the event type (Add or Remove). The added or removed
     * objects are listed via their toString() method.
     * 
     * @param eventType The modification on the collection (ADD or REMOVE)
     * @param objects The objects impacted by the event
     * @return String to be added to the logs
     */
    private String logCollectionInformation(String eventType, Collection objects) {
        if ((objects == null) || (objects.isEmpty()))
            return "";
        
        StringBuffer buffer = new StringBuffer();

        buffer.append("During flush <").append(flushNumber).append("> ").append(eventType).append(" : ");
        for (Iterator iterator = objects.iterator(); iterator.hasNext();) {
            buffer.append(" <").append(iterator.next()).append("> ");
        }

        return buffer.toString();
    }

}
